package com.thinkit.cms.controller.admin;

import com.thinkit.nosql.base.BaseRedisService;
import com.thinkit.security.custom.CustomJwtTokenStore;
import com.thinkit.utils.model.ApiResult;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 系统日志 前端控制器
 * </p>
 *
 * @author lgs
 * @since 2019-08-12
 */
@RestController
@RequestMapping("auth")
public class AuthController  {

    @Autowired
    TokenStore tokenStore;

    @Autowired
    private BaseRedisService baseRedisService;

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public ApiResult logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION) String token){
        // 解析Token
        if(Checker.BeBlank(token)){
            //访问令牌不合法
            return ApiResult.result(7003);
        }
        token = token.replace("bearer","").trim();
        OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
        //token 已过期
        if(oAuth2AccessToken.isExpired()){
            return ApiResult.result(7000);
        }
        if(Checker.BeBlank(oAuth2AccessToken.getValue())){
            //访问令牌不合法
            return ApiResult.result(7003);
        }
        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(oAuth2AccessToken);
        String userName = oAuth2Authentication.getName();
        //获取token唯一标识
        //String jti = (String) oAuth2AccessToken.getAdditionalInformation().get("jti");
        String userId = (String) oAuth2AccessToken.getAdditionalInformation().get("userId");
        baseRedisService.remove(CustomJwtTokenStore.auth+userId);
        return ApiResult.result();
    }

}
